from __future__ import print_function
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import time
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
def compute_accuracy(v_xs, v_ys):
    global prediction
    y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})
    correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1})
    return result
def weight_variable(shape):
    initial=tf.truncated_normal(shape,stddev=0.1)
    return tf.Variable(initial)
def bias_variable(shape):
    initial=tf.constant(0.1,shape=shape)
    return tf.Variable(initial)
def conv2d(x, W):
    return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding="SAME")
def max_pool_2x2(x):
    return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")
with tf.name_scope("input_layer"):
    xs = tf.placeholder(tf.float32, [None, 784],name="X") # 28x28
    ys = tf.placeholder(tf.float32, [None, 10],name="Y")
    x_image=tf.reshape(xs,[-1,28,28,1],name="x_image")
keep_prob = tf.placeholder(tf.float32)
with tf.name_scope("conv1"):
    with tf.name_scope("weights"):
        W_conv1=weight_variable([5,5,1,32])
        tf.summary.histogram("conv1/weigihts",W_conv1);
    with tf.name_scope("biases"):
        b_conv1=bias_variable([32])
        tf.summary.histogram("conv1/biases",b_conv1);
    with tf.name_scope("Wx_Plus_b"):
        h_conv1=tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
    h_pooling1=max_pool_2x2(h_conv1)
with tf.name_scope("conv2"):
    with tf.name_scope("weights"):
        W_conv2=weight_variable([5,5,32,64])
        tf.summary.histogram("conv2/weigihts", W_conv2);
    with tf.name_scope("biases"):
        b_conv2=bias_variable([64])
        tf.summary.histogram("conv2/weigihts", b_conv2);
    with tf.name_scope("Wx_Plus_b"):
        h_conv2=tf.nn.relu(conv2d(h_pooling1,W_conv2)+b_conv2)
    h_pooling2=max_pool_2x2(h_conv2)
with tf.name_scope("hidden_layer"):
    with tf.name_scope("weights"):
        W_fc1=weight_variable([7*7*64,1024])
        tf.summary.histogram("hidden_layer/weigihts", W_fc1);
    with tf.name_scope("biases"):
        b_fc1=bias_variable([1024])
        tf.summary.histogram("hidden_layer/weigihts", b_fc1);
    h_pool2_flat=tf.reshape(h_pooling2,[-1,7*7*64])
    with tf.name_scope("Wx_Plus_b"):
        h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1)
    h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob)
with tf.name_scope("output_layer"):
    with tf.name_scope("weights"):
        W_fc2=weight_variable([1024,10])
        tf.summary.histogram("output_layer/weigihts", W_fc2);
    with tf.name_scope("biases"):
        b_fc2=bias_variable([10])
        tf.summary.histogram("output_layer/biases", b_fc2);
    with tf.name_scope("Wx_Plus_b"):
        prediction=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2)
with tf.name_scope("cross_entropy"):
    cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
                                              reduction_indices=[1]))       # loss
    tf.summary.scalar("loss",cross_entropy)
with tf.name_scope("train"):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
sess = tf.Session()
init = tf.global_variables_initializer()
merged=tf.summary.merge_all()
writer = tf.summary.FileWriter("logs/CNN/", sess.graph)
sess.run(init)
t1=time.time()
for i in range(1001):
    batch_xs= mnist.train.next_batch(100)
    result = sess.run(merged, feed_dict={xs: batch_xs[0], ys: batch_xs[1],keep_prob:0.5})
    writer.add_summary(result, i)
    sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
    if i % 50 == 0:
        print(compute_accuracy(
            mnist.test.images, mnist.test.labels))
t2=time.time()
print("It took %f seconds" % ( t2 - t1))
# Store variable
_W_conv1 = W_conv1.eval(sess)
_b_conv1 = b_conv1.eval(sess)
_W_conv2 = W_conv2.eval(sess)
_b_conv2 = b_conv2.eval(sess)
_W_fc1 = W_fc1.eval(sess)
_b_fc1 = b_fc1.eval(sess)
_W_fc2 = W_fc2.eval(sess)
_b_fc2 = b_fc2.eval(sess)
sess.close()

g_2 = tf.Graph()
with g_2.as_default():
    x_2 = tf.placeholder("float", shape=[None, 784], name="input")

    W_conv1_2 = tf.constant(_W_conv1, name="constant_W_conv1")
    b_conv1_2 = tf.constant(_b_conv1, name="constant_b_conv1")
    x_image_2 = tf.reshape(x_2, [-1, 28, 28, 1])
    h_conv1_2 = tf.nn.relu(conv2d(x_image_2, W_conv1_2) + b_conv1_2)
    h_pool1_2 = max_pool_2x2(h_conv1_2)

    W_conv2_2 = tf.constant(_W_conv2, name="constant_W_conv2")
    b_conv2_2 = tf.constant(_b_conv2, name="constant_b_conv2")
    h_conv2_2 = tf.nn.relu(conv2d(h_pool1_2, W_conv2_2) + b_conv2_2)
    h_pool2_2 = max_pool_2x2(h_conv2_2)

    W_fc1_2 = tf.constant(_W_fc1, name="constant_W_fc1")
    b_fc1_2 = tf.constant(_b_fc1, name="constant_b_fc1")
    h_pool2_flat_2 = tf.reshape(h_pool2_2, [-1, 7 * 7 * 64])
    h_fc1_2 = tf.nn.relu(tf.matmul(h_pool2_flat_2, W_fc1_2) + b_fc1_2)

    W_fc2_2 = tf.constant(_W_fc2, name="constant_W_fc2")
    b_fc2_2 = tf.constant(_b_fc2, name="constant_b_fc2")

    # DropOut is skipped for exported graph.

    y_conv_2 = tf.nn.softmax(tf.matmul(h_fc1_2, W_fc2_2) + b_fc2_2, name="output")

    sess_2 = tf.Session()
    init_2 = tf.global_variables_initializer();
    sess_2.run(init_2)

    graph_def = g_2.as_graph_def()
    tf.train.write_graph(graph_def, "temp/MNIST", 'mnist-graph.pb', as_text=False)

    # Test trained model
    y__2 = tf.placeholder("float", [None, 10])
    correct_prediction_2 = tf.equal(tf.argmax(y_conv_2, 1), tf.argmax(y__2, 1))
    accuracy_2 = tf.reduce_mean(tf.cast(correct_prediction_2, "float"))

    print
    "check accuracy %g" % accuracy_2.eval(
        {x_2: mnist.test.images, y__2: mnist.test.labels}, sess_2)
